//
//  PopAnimation.swift
//  WeiBo
//
//  Created by 江潘 on 15/6/29.
//  Copyright © 2015年 江潘. All rights reserved.
//

import UIKit

class PopAnimation: NSObject,UIViewControllerAnimatedTransitioning,UIViewControllerTransitioningDelegate {
    
    var isPresented = false
    
    var presentedFrame = CGRectZero
    
    // 返回转场控制器
    func presentationControllerForPresentedViewController(presented: UIViewController, presentingViewController presenting: UIViewController, sourceViewController source: UIViewController) -> UIPresentationController?{
        
        let popVc = PopOverPresentationController(presentedViewController: presented, presentingViewController: presenting)
        
        popVc.presentVcFrame = presentedFrame
        
        return popVc
    }
    
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning?{
        
        isPresented = true
        
        return self
    }
    
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning?{
        
        isPresented = false
        
        return self
    }
    
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval{
        return 0.3
    }
    
    func animateTransition(transitionContext: UIViewControllerContextTransitioning){
        
        if isPresented {
            
            let toView = transitionContext.viewForKey(UITransitionContextToViewKey)
            
            toView?.transform = CGAffineTransformMakeScale(1.0, 0)
            
            toView?.layer.anchorPoint = CGPointMake(0.5, 0)
            
            transitionContext.containerView()?.addSubview(toView!)
            
            UIView.animateWithDuration(transitionDuration(transitionContext), delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 10.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in
                toView?.transform = CGAffineTransformMakeScale(1.0, 1.0)
                }, completion: { (_) -> Void in
                    transitionContext.completeTransition(true)
            })
        }
        else {
            
            let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)
            
            UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
                fromView?.transform = CGAffineTransformMakeScale(1.0, 0.0001)
                }, completion: { (_) -> Void in
                    
                    fromView?.removeFromSuperview()
                    transitionContext.completeTransition(true)
            })
        }
    }
}
